package inner_sort

import (
	C "gitee.com/ljfirst/algo-go-sdk/common/constant"
)

/**
 * @author ljfirst
 * @version 1.0
 * @date 2021-06-22 00:09
 * @author—Email ljfirst@mail.ustc.edu.cn
 * @blogURL https://blog.csdn.net/ljfirst
 * @description 冒泡排序
 */

type BubbleSort struct {
	FromHighToLow bool // true表示从高到低排序,默认 false 表示从低到高排序
}

func NewBubbleSort(options ...C.Options) *BucketSort {
	opt := C.NewOptions(options...)
	return &BucketSort{
		FromHighToLow: opt.FromHighToLow,
	}
}

func (m *BubbleSort) SortMethod(array []int) {
	if len(array) < 2 {
		return
	}
	n, flag := len(array), false
	//definition when exchange occurred
	for index := 0; index < n-1; index++ {
		for i := 0; i < n-1-index; i++ {
			if array[i] > array[i+1] {
				array[i], array[i+1] = array[i+1], array[i]
				flag = true // array is already sorted when nothing exchange occurred in a sort
			}
		}
		if !flag {
			break
		}
		flag = false
	}
}

func (m *BubbleSort) Tags() []string {
	return []string{C.Sort}
}

func (m *BubbleSort) GetAttribute() *C.Attribute {
	return &C.Attribute{
		Tags: []string{C.Sort},
		Desc: &C.Desc{
			Name:   "BubbleSort",
			NameCn: "内部排序:冒泡排序",
			ParamsDesc: map[string]string{
				"fromHighToLow": "true表示从高到低排序, 默认 false 表示从低到高排序",
			},
			Example: map[int]string{
				1: "输入[1,3,2],跳用SortMethod方法进行排序后，输出[1,2,3]",
			},
		},
	}
}
